<template>
  <view class="mask">
    <view class="header">
      答题卡
      <view class="close-btn" @click="close"> <uni-icons type="closeempty" size="20"></uni-icons></view>
    </view>
    <view class="status">
      <text class="title">状态说明:</text>
      <view class="circular blue" />
      <text class="sub-title">已作答</text>
      <view class="circular white" />
      <text class="sub-title">未作答</text>
    </view>
    <view class="main">
      <view class="title"> 一、单选题（本大题共{{ singleList.length }}小题，共{{ getTotalScore(singleList) }}分）</view>
      <view class="circular-box">
        <view
          class="circular white"
          v-for="(item, index) in singleList"
          :class="{ blue: isCorrect(item) }"
          :key="item.examinationId"
          @click="link(item.navIndex)"
          >{{ index + 1 }}</view
        >
      </view>
      <view class="title">
        二、多选题（本大题共{{ multipleList.length }}小题，共{{ getTotalScore(multipleList) }}分）</view
      >
      <view class="circular-box">
        <view
          class="circular white"
          v-for="(item, index) in multipleList"
          :class="{ blue: isCorrect(item) }"
          :key="item.examinationId"
          @click="link(item.navIndex)"
          >{{ (singleList.length || 0) + index + 1 }}</view
        >
      </view>
      <view class="title">
        三、判断题（本大题共{{ judgementList.length }}小题，共{{ getTotalScore(judgementList) }}分）</view
      >
      <view class="circular-box">
        <view
          class="circular white"
          v-for="(item, index) in judgementList"
          :class="{ blue: isCorrect(item) }"
          :key="item.examinationId"
          @click="link(item.navIndex)"
          >{{ (singleList.length || 0) + (multipleList.length || 0) + index + 1 }}
        </view>
      </view>
      <view class="title"> 三、填空题（本大题共{{ blankList.length }}小题，共{{ getTotalScore(blankList) }}分）</view>
      <view class="circular-box">
        <view
          class="circular white"
          v-for="(item, index) in blankList"
          :class="{ blue: isCorrect(item) }"
          :key="item.examinationId"
          @click="link(item.navIndex)"
          >{{ (singleList.length || 0) + (multipleList.length || 0) + (judgementList.length || 0) + index + 1 }}
        </view>
      </view>
      <view class="title"> 三、简答题（本大题共{{ qaList.length }}小题，共{{ getTotalScore(qaList) }}分）</view>
      <view class="circular-box">
        <view
          class="circular white"
          v-for="(item, index) in qaList"
          :class="{ blue: isCorrect(item) }"
          :key="item.examinationId"
          @click="link(item.navIndex)"
          >{{
            (singleList.length || 0) +
            (multipleList.length || 0) +
            (judgementList.length || 0) +
            (blankList.length || 1) +
            index +
            1
          }}
        </view>
      </view>
    </view>
    <view class="footer">
      <view class="submit" @click="tipDialogVisible = true">提交试卷</view>
    </view>
    <OnlineExamTipDialog v-model="tipDialogVisible" @confirm="handleSubmit" :type="noDoneNum ? '' : 'primary'">
      <view>{{ noDoneNum ? '温馨提示' : '恭喜您' }}</view>
      <view>{{ noDoneNum ? `您还有${noDoneNum}题未做，确认交卷吗` : '题目已全部答完，确认交卷吗' }}</view>
    </OnlineExamTipDialog>
    <examination-dialog
      v-model="examinationDialogVisible"
      :status="examinationDialogStatus"
      :data="examinationResult"
      @ended="handleEnded"
    />
  </view>
</template>

<script>
import { getTestQuestions, submitEaxm } from '@/api/educational-training/online-examination'
import { mapMutations, mapState, mapActions } from 'vuex'
import { get, sum } from 'lodash'
import TipDialog from './components/TipDialog'
import ExaminationDialog from './components/ExaminationDialog'
import { examinationStatus } from '@/utils/constant'
import OnlineExamTipDialog from './components/OnlineExamTipDialog'

export default {
  name: 'online-answer-sheet',
  components: {
    TipDialog,
    ExaminationDialog,
    OnlineExamTipDialog
  },

  data() {
    return {
      isSubmit: false,
      examinationStatus,
      examPlanId: null,
      paperData: {
        judgementList: [],
        multipleTitle: [],
        singleTitle: [],
        blankList: [],
        qaList: []
      },
      tipDialogVisible: false,
      examinationDialogVisible: false,
      examinationDialogStatus: examinationStatus.PAUSE,
      examinationResult: {}
    }
  },

  onLoad({ examPlanId }) {
    this.examPlanId = examPlanId
  },

  onShow() {
    this.fetchData()
  },

  computed: {
    ...mapState({
      examDetailList: (state) => state.onlineExam.examDetailList
    }),
    singleList() {
      return get(this.paperData, 'singleList', []).map((item, index) => ({
        ...item,
        navIndex: index
      }))
    },
    multipleList() {
      return get(this.paperData, 'multipleList', []).map((item, index) => ({
        ...item,
        navIndex: index + this.singleList.length
      }))
    },
    noDoneNum() {
      return this.examDetailList.filter(
        (item) =>
          ((item.type === '1' || item.type === '2' || item.type === '3') && !item.selectOptionIds.length) ||
          (item.type === '4' && !Object.values(item.optionAnswers).some((oItem) => oItem)) ||
          (item.type === '5' && !item.answer)
      ).length
    },
    judgementList() {
      return get(this.paperData, 'judgementList', []).map((item, index) => ({
        ...item,
        navIndex: index + this.singleList.length + this.multipleList.length
      }))
    },
    blankList() {
      return get(this.paperData, 'blankList', []).map((item, index) => ({
        ...item,
        navIndex: index + this.singleList.length + this.multipleList.length + this.judgementList.length
      }))
    },
    qaList() {
      return get(this.paperData, 'qaList', []).map((item, index) => ({
        ...item,
        navIndex:
          index + this.singleList.length + this.multipleList.length + this.judgementList.length + this.blankList.length
      }))
    }
  },

  methods: {
    ...mapActions(['submitPapel']),
    ...mapMutations(['setCurrentPaperIndex']),
    async fetchData() {
      const { data } = await getTestQuestions(this.examPlanId)
      this.paperData = data
      let singleList = []
      let multipleList = []
      let judgementList = []
      let blankList = []
      let qaList = []
      for (let i of this.paperData.questionTypes) {
        if (i.questionType === '1') {
          for (let j of i.questionList) {
            j.score = i.score
            j.totalNum = i.totalNum
            j.totalScore = i.totalScore
            j.type = i.questionType
            singleList.push(j)
          }
        } else if (i.questionType === '2') {
          for (let j of i.questionList) {
            j.score = i.score
            j.totalNum = i.totalNum
            j.totalScore = i.totalScore
            j.type = i.questionType
            multipleList.push(j)
          }
        } else if (i.questionType === '3') {
          for (let j of i.questionList) {
            j.score = i.score
            j.totalNum = i.totalNum
            j.totalScore = i.totalScore
            j.type = i.questionType
            judgementList.push(j)
          }
        } else if (i.questionType === '4') {
          for (let j of i.questionList) {
            j.score = i.score
            j.totalNum = i.totalNum
            j.totalScore = i.totalScore
            j.type = i.questionType
            blankList.push(j)
          }
        } else if (i.questionType === '5') {
          for (let j of i.questionList) {
            j.score = i.score
            j.totalNum = i.totalNum
            j.totalScore = i.totalScore
            j.type = i.questionType
            qaList.push(j)
          }
        }
      }
      this.paperData.singleList = singleList
      this.paperData.multipleList = multipleList
      this.paperData.judgementList = judgementList
      this.paperData.blankList = blankList
      this.paperData.qaList = qaList
    },
    getTotalScore(list) {
      return sum(list.map((item) => item.score))
    },
    close() {
      uni.navigateBack()
    },
    isCorrect({ navIndex, type }) {
      if (type === '1' || type === '2' || type === '3') {
        return get(this.examDetailList, `${navIndex}.selectOptionIds.length`, 0)
      } else if (type === '4') {
        const item = this.examDetailList[navIndex]
        return item.optionAnswers ? Object.values(item.optionAnswers).some((oItem) => oItem) : false
      } else if (type === '5') {
        const item = this.examDetailList[navIndex]
        return item.answer
      }
    },
    link(index) {
      this.setCurrentPaperIndex(index)
      this.close()
    },
    async handleSubmit() {
      // 快速点击会导致重复提交
      if (this.isSubmit) {
        return
      }
      this.isSubmit = true
      try {
        await submitEaxm(this.examPlanId)
      } catch (err) {
        console.log(err)
      }
      getTestQuestions(this.examPlanId)
        .then(({ data }) => {
          if (data.score < data.passScore) {
            this.examinationDialogStatus = examinationStatus.FAIL
          } else {
            this.examinationDialogStatus = examinationStatus.SUCCESS
          }
          this.examinationResult = {
            score: data.score,
            errors: data.errorCount,
            qualifying: this.paperData.passScore
          }
          this.examinationDialogVisible = true
        })
        .finally(() => {
          this.isSubmit = false
        })
    },
    handleEnded() {
      uni.navigateBack({
        delta: 2
      })
    }
  }
}
</script>
  
<style scoped lang="scss" type="text/scss">
.mask {
  position: fixed;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: #fff;
  padding-top: 50rpx;
}
.header {
  position: relative;
  height: 88rpx;
  line-height: 88rpx;
  width: 100%;
  font-size: 36rpx;
  font-weight: bold;
  color: #333333;
  text-align: center;

  .close-btn {
    position: absolute;
    top: 0;
    left: 30rpx;
  }
}
.status {
  display: flex;
  align-items: center;
  font-size: 26rpx;
  height: 77rpx;
  padding-left: 30rpx;
  background: #f5f5f5;

  .title {
    color: #333333;
    margin-right: 10rpx;
  }
  .sub-title {
    color: #666666;
    margin-right: 30rpx;
  }
  .circular {
    margin-right: 10rpx;
  }
}
.circular {
  width: 34rpx;
  height: 34rpx;
  border-radius: 50%;
}
.white {
  background: #ffffff;
  border: 1px solid #bbbbbb;
  color: #999999;
}
.blue {
  background: #ebf2f5;
  border: 1px solid #88b4c4;
  color: #88b4c4;
}
.red {
  color: #a14430;
  background: #efdedb;
  border: 1px solid #a14430;
}
.main {
  overflow: auto;
  height: calc(100vh - 400rpx);
  padding: 30rpx 10rpx 40rpx;

  .circular {
    width: 90rpx;
    height: 90rpx;
    margin-left: 30rpx;
    margin-top: 30rpx;
    text-align: center;
    line-height: 90rpx;
  }
  .circular-box {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 50rpx;
  }
}
.footer {
  position: fixed;
  bottom: 40rpx;
  left: 50%;
  transform: translateX(-50%);
  .submit {
    text-align: center;
    width: 600rpx;
    height: 98rpx;
    line-height: 98rpx;
    font-size: 36rpx;
    color: #ffffff;
    background: #454a5e;
    border-radius: 50rpx 50rpx 50rpx 50rpx;
  }
}
</style>